/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.authcenter.helper.impl;

import com.alibaba.fastjson.JSONObject;
import com.robam.cloud.authcenter.helper.ThirdAuthGateway;
import com.robam.cloud.authcenter.helper.WechatAccessTokenGateway;
import com.robam.cloud.authcenter.manager.WechatAccessTokenManager;
import com.robam.cloud.common.bean.authcenter.dto.FaceParam;
import com.robam.cloud.common.bean.authcenter.entity.AuthPlatform;
import com.robam.cloud.common.bean.authcenter.entity.FaceRes;
import com.robam.cloud.common.bean.common.Constant;
import com.robam.cloud.common.bean.restful.entity.ServiceException;
import com.robam.cloud.common.bean.usercenter.entity.LoginAccount;
import com.robam.cloud.common.bean.usercenter.entity.User;
import com.robam.cloud.common.bean.usercenter.entity.UserSession;
import com.robam.cloud.common.util.RequestUtil;
import com.robam.cloud.common.util.UuidUtil;
import com.robam.cloud.common.util.wechat.WechatUser;
import com.robam.cloud.common.util.wechat.WechatUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2020-07-20 15:49
 * @Version 1.0
 */
@Component
public class WechatAuthGateway extends ThirdAuthGateway {
    @Autowired
    WechatUtil wechatUtil;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    WechatAccessTokenManager wechatAccessTokenManager;

    @Override
    public UserSession getUserSession(AuthPlatform authPlatform, JSONObject request, HttpServletRequest httpServletRequest) {
        String code = request.getString("code");
        if (StringUtils.isNotEmpty(code)) {
            WechatUser wechatUser = wechatUtil.getWechatUserId(authPlatform.getAppId(), authPlatform.getAppSecret(), code);
            LoginAccount loginAccount = LoginAccount.builder()
                    .platformId(authPlatform.getId())
                    .accountOpenid(wechatUser.getOpenid())
                    .nickname(wechatUser.getNickname())
                    .sex(wechatUser.getSex())
                    .zcip(RequestUtil.getIpAddress(httpServletRequest))
                    .zcsj(new Date())
                    .build();
            User user = null;
            return UserSession.builder().user(user).loginAccount(loginAccount).build();
        } else {
            return null;
        }
    }

    @Override
    public FaceParam getFaceParam(AuthPlatform authPlatform, String certNo, String certType, String certName, String sfbr, String expireTime, String token) {
        String bizNo = UuidUtil.createUuid(Constant.FACEBIZNO);
        FaceParam faceParam = FaceParam.builder()
                .faceBizNo(bizNo)
                .faceSfzmhm(certNo)
                .faceSfzmmc(certType)
                .faceXm(certName)
                .build();
        redisTemplate.opsForValue().set(Constant.FACEBIZNO + ":" + token, bizNo, Long.parseLong(expireTime), TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(Constant.FACEBIZNO + ":" + bizNo, false, Long.parseLong(expireTime), TimeUnit.MINUTES);
        return faceParam;
    }

    @Override
    public void verifyFaceResult(AuthPlatform authPlatform, FaceRes faceRes, String token) {
        String bizNo = String.valueOf(redisTemplate.opsForValue().get(Constant.FACEBIZNO + ":" + token));
        if (faceRes.getErr_code().equals(FaceRes.RESULT_CODE_SUCCESS)) {
            WechatAccessTokenGateway wechatAccessTokenGateway = wechatAccessTokenManager.callAccessTokenMeth(authPlatform.getAccesstokentype());
            String accessToken = wechatAccessTokenGateway.requestToken(authPlatform);
            String base64pic = wechatUtil.httpRequestofBytes(accessToken, "POST",
                    "{\"identify_id\":\"" + faceRes.getVerify_result() + "\"}");
            //todo 证据上传oss
            redisTemplate.opsForValue().set(Constant.FACEBIZNO + ":" + bizNo, true);
            return;
        }
        String errMsg = faceRes.getErr_msg();
        if ("system:function_not_exist".equals(errMsg)) {
            throw new ServiceException("请升级微信版本!");
        } else {
            throw new ServiceException("微信人脸识别验证失败!");
        }
    }


    @Override
    public String getMediaUrl(AuthPlatform authPlatform, String serverId) {
        WechatAccessTokenGateway wechatAccessTokenGateway = wechatAccessTokenManager.callAccessTokenMeth(authPlatform.getAccesstokentype());
        String accessToken = wechatAccessTokenGateway.requestToken(authPlatform);
        return wechatUtil.getMediaUrl(accessToken, serverId);
    }
}
